<?php

namespace App\Http\Controllers\Admin\Base;

use App\Http\Controllers\Controller;
use App\Models\EmailModel;
use Illuminate\Http\Request;

class Email extends Controller
{
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $descr = trim($request->input('descr', ''));
        $email = trim($request->input('email', ''));

        $query = EmailModel::query();

        if($descr) $query->where('descr', 'like', '%'.$descr.'%');
        if($email) $query->where('email', 'like', '%'.$email.'%');

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'descr' => $item->descr,
                'email' => $item->email,
                'create_user' => $item->creator?->staff?->name ??  '',
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request) {
        $auth = $request->get('auth');
        $descr = trim($request->input('descr', ''));
        $email = trim($request->input('email', ''));

        if(!$descr) return $this->error('请输入描述');
        if(!$email) return $this->error('请输入邮箱');
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) return $this->error('邮箱格式不正确');

        $model = new EmailModel();
        $model->descr = $descr;
        $model->email = $email;
        $model->creator_id = $auth->id;
        $model->save();

        return $this->success();
    }

    public function update(Request $request, $id) {
        $auth = $request->get('auth');
        $descr = trim($request->input('descr', ''));
        $email = trim($request->input('email', ''));

        if(!$descr) return $this->error('请输入描述');
        if(!$email) return $this->error('请输入邮箱');
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) return $this->error('邮箱格式不正确');

        $model = EmailModel::find($id);
        if(!$model) return $this->error('邮箱不存在');

        $model->descr = $descr;
        $model->email = $email;
        $model->save();

        return $this->success();
    }

    public function del(Request $request, $id) {
        EmailModel::where('id', $id)->delete();

        return $this->success();
    }

}
